var hex, sha1, sign;

sha1 = function(str) {
  var buffer;
  // We transform the string into an arraybuffer.
  buffer = new TextEncoder('utf-8').encode(str);
  return crypto.subtle.digest('SHA-1', buffer).then(function(hash) {
    return hex(hash);
  });
};

hex = function(buffer) {
  var hexCodes, i, paddedValue, padding, stringValue, value, view;
  hexCodes = [];
  view = new DataView(buffer);
  i = 0;
  while (i < view.byteLength) {
    // Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
    value = view.getUint32(i);
    // toString(16) will give the hex representation of the number without padding
    stringValue = value.toString(16);
    // We use concatenation and slice for padding
    padding = '00000000';
    paddedValue = (padding + stringValue).slice(-padding.length);
    hexCodes.push(paddedValue);
    i += 4;
  }
  // Join all the hex strings into one
  return hexCodes.join('');
};

sign = async(ticket, url) => {
  var nonce, signature, str, timestamp;
  nonce = Math.random().toString(36).substr(2, 15);
  timestamp = parseInt(new Date().getTime());
  str = "jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + location.href.split("#", 1)[0];
  signature = (await sha1(str));
  return {
    signature,
    timestamp,
    nonceStr: nonce
  };
};

$.when($.get("//wxticket.xvc.com/ticket.txt?" + (new Date() / 62e5).toString(36)), $.getScript("//res.wx.qq.com/open/js/jweixin-1.6.0.js")).done(([ticket]) => { // ticket过期时间是7200秒，刷新周期是15分钟，所以获取的ticket最小有效期为7200-15*60-请求响应时间
  return sign(ticket).then(function(config) {
    var jsApiList;
    jsApiList = "updateTimelineShareData updateAppMessageShareData onMenuShareTimeline onMenuShareAppMessage onMenuShareQQ onMenuShareWeibo onMenuShareQZone".split(' ');
    wx.config(Object.assign(config, {
      appId: 'wxab95844927471714',
      jsApiList: jsApiList
    }));
    return wx.ready(function() {
      return wx.checkJsApi({
        jsApiList,
        success: ({checkResult}) => {
          var desc, imgUrl, k, o, page, ref, title, v, x;
          page = JSON.parse($("script[type='application/ld+json']").html());
          ({
            headline: title,
            description: desc
          } = page);
          imgUrl = "https://font.xvc.com/x";
          //img = page.image?.url
          //if img and (img.indexOf('600B5iVR_') < 0)
          //  imgUrl= "https:"+img+"?imageView2/1/w/300/h/300"
          o = {
            desc,
            imgUrl,
            link: location.href,
            title,
            success: () => {}
          };
          ref = Object.entries(checkResult);
          for (x of ref) {
            [k, v] = x;
            if (v) {
              wx[k](o);
            }
          }
        }
      });
    });
  });
});
